// 404: 目录层级发生错误
// 502: 文件层级发生错误
// 200: 读写成功
// 400: 代表发生错误


const ioWriterPlus = (data) => {
	const ext = new Date()
		.getTime()
		.toString()
		.substr(8);

	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL('_downloads', entry => {
			entry.getFile(`config_${ext}.json`, {
				create: true
			}, fileEntry => {
				fileEntry.file(file => {
					fileEntry.createWriter(
						writer => {
							writer.write(data ? JSON.stringify(data) : new Date().toISOString());
							resolve(200);
						},
						e => reject(502)
					);
				});
			}, e => reject(404));
		});
	});
}

const ioReaderPlus = (file) => {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL(`_downloads/${file}`, fileEntry => {
			fileEntry.file(file => {
				const fileReader = new plus.io.FileReader();
				fileReader.readAsText(file, 'utf-8');
				fileReader.onloadend = evt => {
					resolve(evt.target.result);
				};
			}, e => reject(502));
		}, e => reject(404));
	});
}

const ioRemovePlus = () => {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL('_downloads', entry => {
			entry.removeRecursively(
				suc => resolve(200),
				e => reject(502)
			);
		}, e => reject(404));
	})
}

const ioSourcePlus = (path = '_downloads') => {
	let results = [];
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL('_downloads', entry => {
			const directoryReader = entry.createReader();
			directoryReader.readEntries(files => {
				for (const file of files) {
					if (file.isFile) {
						results.push(file.name);
					}
					resolve(results || []);
				}
			}, e => reject(502));
		}, e => reject(404))
	})

}


const date2time = (space = 100, n = 0) => {
	return new Date().getTime() - n * space;
}

export {
	ioWriterPlus,
	ioReaderPlus,
	ioRemovePlus,
	ioSourcePlus,
	date2time
}
